package com.wisdytech.ccdserver.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.cloud.apigateway.sdk.utils.Client;
import com.cloud.apigateway.sdk.utils.Request;
import com.wisdytech.ccdserver.bucket.dto.ResultDto;
import com.wisdytech.ccdserver.bucket.model.Bucket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author svolt
 */

@Component
@Slf4j
public class HttpUtils {
    @Value("${trace.api.baseUrl}")
    private  String baseUrl;
    @Value("${trace.api.tokenUrl}")
    private  String tokenUrl;
    @Value("${trace.api.appId}")
    private  String apiAppId;
    @Value("${trace.api.secret}")
    private  String apiSecret;

    public String obtainApiToken() {
        String token = "";
        try {
            Object tokenObject = RedisUtil.redis.opsForValue().get("trace-token");
            if (tokenObject == null) {
                String tokenDataUrl = baseUrl.concat(tokenUrl);
                String appId = apiAppId;
                String secret = apiSecret;
                token = getTraceToken(tokenDataUrl, appId, secret);
            } else {
                token = tokenObject.toString();
            }
            //获取token
//            token = HttpUtils.getTraceToken(tokenDataUrl,appId,secret);
            log.info("========trace token=============" + token);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return token;
    }


    /**
     * @param
     * @param token
     * @Description: 获取ccdServer的信息
     * @Param: * @param url
     * @return: * @return com.wisdytech.ccdserver.bucket.dto.ResultDto
     * @Author: SV00216491
     * @Date: 2024/3/31  13:51
     */
    public String apiPostByJson(String url, String jsonString, String token) {
        CloseableHttpClient httpClient = null;
        String result = "";
        try {
            //创建post请求
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            if (StringUtils.isNotEmpty(jsonString)) {
                StringEntity requestEntity = new StringEntity(jsonString, "utf-8");
                httpPost.setEntity(requestEntity);
            }
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
            if (StringUtils.isNotEmpty(token)) {
                httpPost.setHeader("Authorization", token);
            }
            //发送请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public ResultDto searchFromBigData(String url, Map<String, Object> headers, String token) {
        List<NameValuePair> params = new ArrayList<>();
        CloseableHttpClient httpClient = null;
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String msg = "";
        String result = "";
        String executeSql = "";
        String errorMsg = "";
        ResultDto resultDto = new ResultDto();
        JSONObject object = null;
        try {
            if (headers != null && headers.size() != 0) {
                for (Map.Entry<String, Object> entry : headers.entrySet()) {
                    params.add(new NameValuePair() {
                        @Override
                        public String getName() {
                            return entry.getKey();
                        }

                        @Override
                        public String getValue() {
                            return String.valueOf(entry.getValue());
                        }
                    });
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("Authorization", token);
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (HttpURLConnection.HTTP_UNAUTHORIZED == statusCode) {
                String tokenDataUrl = baseUrl.concat(tokenUrl);
                String appId = apiAppId;
                String secret = apiSecret;
                token = this.getTraceToken(tokenDataUrl, appId, secret);
                //重置token
                httpPost.setHeader("Authorization", token);
                response = httpClient.execute(httpPost);
                statusCode = response.getStatusLine().getStatusCode();
            }
            if (HttpURLConnection.HTTP_OK == statusCode) {
                HttpEntity entity = response.getEntity();
                msg = EntityUtils.toString(entity);
                if (StringUtils.isNotEmpty(msg)) {
                    object = JSONObject.parseObject(msg);
                    if (object.get("datas") != null) {
                        object = JSONObject.parseObject(object.get("datas").toString());
                        result = object.get("result") == null ? "" : object.get("result").toString();
                        resultDto.setResult(result);
                        int count = object.get("count") == null ? 0 : Integer.parseInt(object.get("count").toString());
                        resultDto.setCount(count);
                        executeSql = object.get("executeSQL") == null ? "" : object.get("executeSQL").toString();
                        resultDto.setExecuteSql(executeSql);
                        errorMsg = object.get("errorMsg") == null ? "" : object.get("errorMsg").toString();
                        resultDto.setErrorMsg(errorMsg);
                    }
                }
            }
        } catch (IOException e) {
            log.error("错误信息{}");
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultDto;
    }

    /**
     * 获取token
     *
     * @param tokenUrl
     * @param appId
     * @param secret
     * @return
     */
    public String getTraceToken(String tokenUrl, String appId, String secret) {
        String token = "";
        String resultStr = "";
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("appid", appId);
        queryParams.put("secret", secret);
        Object[] array = queryParams.entrySet().stream().map(e -> StringUtils.join(e.getKey(), "=", URLEncoder.encode(e.getValue().toString()))).toArray();
        String str = StringUtils.join("?", StringUtils.join(array, "&"));
        log.info("=============token resultStr===============" + resultStr);
        resultStr = apiPostByJson(tokenUrl.concat(str), "", null);
        if (StringUtils.isNotEmpty(resultStr)) {
            JSONObject object = JSONObject.parseObject(resultStr);
            token = (String) object.get("token");
            RedisUtil.redis.opsForValue().set("trace-token", token, 24, TimeUnit.HOURS);
        }
        return token;
    }

}
